package com.china08.yxyapi.api.home.weikecheng;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.user.YxyUserMark;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.service.yxweike.YxyWeikeService;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 微课前台页面----搜索页
 * 
 */
@CrossOrigin
@RestController
public class WeikeSrhController extends YxyApiBaseController {

    @Autowired
    private YxyWeikeService weikeService;

    @Autowired
    private MongoTemplate mt;

    @ResponseBody
    @RequestMapping(value = "/api_yw/home/weike/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {

        reqModel.check();

        Pageable pageable = new PageRequest(reqModel.page, reqModel.size);
        Page<ElasticYxyResResource> page = null;

        reqModel.keyword = new String(Base64.decodeBase64(reqModel.keyword));
        reqModel.keyword = reqModel.keyword.toLowerCase();

        // ## 1 --按短语
        // 区域微课
        if (StringUtils.equals(reqModel.weikeType, "1")) {
            page = weikeService.findResourceEdu("", "", "", reqModel.areaId, reqModel.keyword, false, "", "", pageable);
        }
        // 本校微課--(已登录状态)
        if (StringUtils.equals(reqModel.weikeType, "2")) {
            String schoolId = reqModel.schoolId;
            Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "学校id不能为空");
            page = weikeService.findResourceSch("", "", "", schoolId, reqModel.keyword, false, "", "", pageable);
        }
        // 云校微課
        if (StringUtils.equals(reqModel.weikeType, "3")) {
            page = weikeService.findResourceYx("", "", "", reqModel.keyword, false, "", "", 0, 2, pageable);
        }
        List<RespModel> list = new ArrayList<RespModel>();
        for (ElasticYxyResResource resResource : page) {
            RespModel respModel = new RespModel();
            String weikeId = resResource.getId();
            respModel.weikeId = weikeId;
            respModel.cover = resResource.getCover();
            respModel.title = resResource.getTitle();
            respModel.uploaderName = resResource.getUploaderName();
            respModel.pv = resResource.getPv();
            respModel.duration = YxyResUtil.getDurationString(resResource);
            respModel.isVip = resResource.getIsVip();
            respModel.isHighQualityYx = resResource.getIsHighQualityYx();
            // 相关知识点
            List<String> knowNames = resResource.getKnowNames();
            List<String> knowNames2 = new ArrayList<String>();
            for (String knowName : knowNames) {
                knowName = resResource.getStageName() + "/" + resResource.getWeikeSubjectName() + "/" + knowName;
                knowNames2.add(knowName);
            }
            respModel.knowNames = StringUtils.join(knowNames2, ",");
            respModel.mark = resResource.getMark() == 0 ? 5
                    : new BigDecimal(resResource.getMark()).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
            respModel.intro = resResource.getIntro();
            // 已评数量
            Long markCount = mt.count(new Query().addCriteria(Criteria.where("resId").is(weikeId)), YxyUserMark.class);
            respModel.markCount = markCount;
            // 已收藏数量
            // Long favCount = mt.count(
            // new
            // Query().addCriteria(Criteria.where("resId").is(weikeId).and("resType").is("01")),
            // YxyUserFavor.class);
            Long favCount = resResource.getFavoriteCount();
            respModel.favCount = favCount;
            // 上传时间
            SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
            respModel.uploadTime = sdFormat.format(resResource.getUploadTime());
            list.add(respModel);
        }
        Page<RespModel> pageImpl = new PageImpl<RespModel>(list, pageable, page.getTotalElements());
        return pageImpl;
    }

    protected static class ReqModel extends YxyApiPageReqModel {

        public String keyword;// 关键字

        public String weikeType;// 微课范围类型：区域微课1,本校微课2,云校微课3

        public String schoolId;// 当前用户的学校id
        // 区域Id码
        public String areaId;

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(weikeType, null), "微课共享范围不能为空");
        }

    }

    protected static class RespModel extends YxyApiRespModel {

        public String weikeId;// 微课Id

        public String cover;// 封面

        public String duration;// 时长

        public String title;// 标题

        public String uploaderName;// 上传者

        public Long pv;// 浏览量

        public String knowNames;// 相关知识点

        public Float mark;// 评分

        public Long markCount;// 多少人已评

        public Long favCount;// 多少人已收藏

        public String intro;// 微课简介

        public String uploadTime;// 上传时间

        public Boolean isVip = false;

        public Integer isHighQualityYx = 0;

    }

}
